"""
文件模块，封装读取各种格式文件，转换读取内容为指定格式。
"""
import os, configparser, yaml
from utils.log import Logger
from config.config import TEST_FILE

_module_name_ = os.path.basename(__file__).split('.')[0]
_logger = Logger.get_logger(_module_name_)

class FileUtils:
    '''
    读取各类格式文件，excel、yaml、ini、conf等
    '''
    module_name_ = os.path.basename(__file__).split('.')[0]
    logger = Logger.get_logger(module_name_)

    def __init__(self, path):
        # _logger = LoggerUtils().get_logger(cls.module_name_)
        # module_name_ = os.path.basename(__file__).split('.')[0]
        # _logger = Logger.get_logger(module_name_)
        self._path = None
        try:
            if os.path.exists(path):
                self._path = path
            else:
                raise FileNotFoundError('文件不存在！')
        except Exception as e:
            _logger.error(f'{path}文件路径错误' + str(e))
        self._data = None

    @property
    def data(self):
        # 如果是第一次调用data，读取yaml文档，否则直接返回之前保存的数据
        if not self._data:
            with open(self._path, 'rb') as f:
                self._data = list(yaml.safe_load_all(f))  # load后是个generator，用list组织成列表
        return self._data

    def read_all_txt(self):
        with open(self._path, encoding='utf-8') as file:
            contents = file.read()
        return contents

    def read_txt(self):
        li = []
        # try:
        if self._path != None:
            with open(self._path, encoding='utf-8') as file:
                contents = file.readlines()
            _logger.info('txt文件读取成功')
            for content in contents:
                if not content.startswith('#'):  # 如果文本中以#开始，则认为是注释
                    li.append(content.strip())
            # except Exception as e:
            #     _logger.error(f'{self._path}文件路径错误')
        return li

    def read_excel(self, sheet_name):
        '''
        根据sheet_name读取excel的方法
        :param sheet_name: sheet页的名称
        :return: 某个sheet页中的所有内容的对象
        '''
        import xlrd
        # if self._path != None:
        #     workbook = xlrd.open_workbook(self._path)  # 读取excel
        contents = None
        try:
            if self._path != None:
                workbook = xlrd.open_workbook(self._path)  # 读取excel
                contents = workbook.sheet_by_name(sheet_name)  # 根据sheet页的名称读取其内容
                _logger.info('excel文件读取成功')
        except Exception as e:
            _logger.error(f'{sheet_name}参数错误' + str(e))
            contents = None
        return contents

    def get_json(self):
        """
        读取json格式文件中的内容
        :return:json文件内容
        """
        import json5
        contents = None
        if self._path != None:
            # try:
            with open(self._path ,encoding='utf-8') as file:
                contents = json5.load(file)
            _logger.info('json文件读取成功')
            # except Exception as e:
            #     _logger.error(f'{self._path}文件路径错误')
        return contents

    def get_ini_option_value(self, section, option):
        """
        读取配置文件中某个节点下option的值
        :param section:section节点名
        :param option:option名
        :return:给定section节点名下option名的值
        """
        cp = configparser.ConfigParser()
        result = None
        try:
            if self._path is not None:
                cp.read(self._path, encoding='utf-8')
                result = eval(cp.get(section, option))
                _logger.info(f'ini文件{option}读取成功')
        except Exception as e:
            _logger.error(f'{section}、{option}参数错误' + str(e))
        return result

    def get_ini_section(self, section):
        """
        读取某个配置文件下节点中的全部内容，返回的是列表+元组
        :param section:section节点名
        :return:给定section节点名下内容
        """
        contents = None
        if self._path != None:
            try:
                cp = configparser.ConfigParser()
                cp.read(self._path, encoding='utf-8')
                contents = cp.items(section)
                _logger.info('ini文件读取成功')
            except Exception as e:
                _logger.error(f'{section}参数错误' + str(e))
        return contents




class ParserUtils:
    '''
    数据解析类，封装将各种格式的文件解析为目标格式
    '''
    def __init__(self, path):
        """
        初始化方法
        :param path: 测试信息配置文件的路径
        """
        self.module_name_ = os.path.basename(__file__).split('.')[0]
        _logger = Logger.get_logger(self.module_name_)
        self._path = path
        self.file = FileUtils(path)
        self.ini_file = FileUtils(TEST_FILE)
        # _logger = LoggerUtils().get_logger(module_name)

    def parse_test_info_by_ini(self, section):
        """
        通过读取配置文件获取excel测试数据文件中的测试信息
        :param section: 节点名
        :return:节点名下所有元素，列表套字典
        """

        conf = {}
        contents = self.ini_file.get_ini_section(section)
        if contents != None:
            for content in contents:
                conf[content[0]] = content[1]

            if conf != None:
                contents = self.file.read_excel(conf['sheet_name'])
        li = []
        if contents != None:
            for i in range(int(conf['start_row']), int(conf['end_row'])):
                test_data = contents.cell(i, int(conf['test_data_col'])).value
                # expect = contents.cell(i, int(conf['expect_col'])).value
                di = {}
                temp = str(test_data).split('\n')
                for t in temp:
                    di[t.split('=')[0]] = t.split('=')[1]
                # di['expect'] = expect
                li.append(di)

        return li

    def parse_test_info_dict(self, section):
        """
        通过读取配置文件获取excel测试数据文件中的测试信息
        :param section: 节点名
        :return:节点名下所有元素，列表套字典
        """

        conf = {}
        contents = self.ini_file.get_ini_section(section)
        if contents != None:
            for content in contents:
                conf[content[0]] = content[1]
                # print(conf)

            if conf != None:
                contents = self.file.read_excel(conf['sheet_name'])
                # print(contents)
        li = []
        try:
            if contents != None:
                for i in range(int(conf['start_row']), int(conf['end_row'])):
                    test_data = contents.cell(i, int(conf['test_data_col'])).value
                    expect = contents.cell(i, int(conf['expect_col'])).value
                    case_id = contents.cell(i, int(conf['case_id_col'])).value
                    module_name = contents.cell(i, int(conf['module_name_col'])).value
                    case_desc = contents.cell(i, int(conf['case_desc_col'])).value
                    test_type = contents.cell(i, int(conf['test_type_col'])).value
                    api_url = contents.cell(i, int(conf['api_url_col'])).value
                    request_method = contents.cell(i, int(conf['request_method_col'])).value

                    info = {}
                    di = {}
                    if test_data != '':
                        temp = str(test_data).split('\n')
                        for t in temp:
                            di[t.split('=')[0]] = t.split('=')[1]
                    info['case_id'] = case_id
                    info['module_name'] = module_name
                    info['case_desc'] = case_desc
                    info['test_type'] = test_type
                    info['api_url'] = api_url
                    info['request_method'] = request_method
                    info['test_data'] = di
                    info['expect'] = expect
                    li.append(info)
        except Exception as e:
            _logger.error('测试信息配置文件test_info.cnf错误' + e.__str__())

        return li

    def parse_dict_by_tuple(self, section):
        """
        将读取的配置文件某个section的结果转化为字典
        :param section:
        :return:
        """
        # if self._path != None:
        #     di = {}
        #     try:
        di = {}
        contents = self.file.get_ini_section(section)
        if contents != None:
            for content in contents:
                di[content[0]] = content[1]
            # except Exception as e:
            #     _logger.error(f'{section}参数错误')

        return di

if __name__ == '__main__':
    # obj = FileUtils('../project/woniuboss/data/ui_case.xlsx').read_excel('login')
    # print(obj)
    r = ParserUtils('../data/ui_case.xlsx').parse_test_info_dict('rob_tenants')
    print(r)

    pass
